package com.itheimaoa.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.junit.Test;

public class UploadUtils {

	public static String getExt(String fileName) {
		if (fileName != null && "" != fileName) {
			return fileName.substring(fileName.lastIndexOf("."));
		}
		return null;
	}

	public static void deleteFile(String fileRealPath) {
		if (fileRealPath != null && "" != fileRealPath) {
			File file = new File(fileRealPath);
			if (file.exists()) {
				file.delete();
			}
		}
	}
	@Test
    public void test(){
		deleteFile("D:/java/websoft/tomcat/tomcat-EXAMPLE/webapps/itcastStrutsGird/WEB-INF/upload/2013/06/23/8113f6f7-1622-423f-8bfb-8567de378611.xls");
    }
	public static String saveUploadFile(File upload) {
		return saveUploadFile(upload, ".xls");
	}

	public static String saveUploadFile(File upload, String fileExt) {
		// 把日期格式化成字符串的一个帮助类
		SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
		/*
		 * 得到upload文件夹的绝对路径 ServletActionContext.getServletContext() =
		 * C:\Program Files\Apache Software Foundation\Tomcat
		 * 6.0\webapps\itcastoa823\WEB-INF/upload/2012\02\16\aaaaadfasdf
		 */
		String basePath = ServletActionContext.getServletContext().getRealPath(
				"/WEB-INF/upload");
		// 把日期类型格式化为"/yyyy/MM/dd/"这种形式的字符串
		String subPath = sdf.format(new Date());
		// 如果文件夹不存在，就创建文件夹
		File dir = new File(basePath + subPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		// String path = basePath+"/"+this.uploadFileName;
		// UUID.randomUUID().toString()能够保证名字的唯一性
		String path = basePath + subPath + UUID.randomUUID().toString()
				+ fileExt;
		File dest = new File(path);
		// 把文件移动到dest处
		upload.renameTo(dest);
		return path;
	}
}
